/*
* Tencent is pleased to support the open source community by making Mars available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the MIT License (the "License"); you may not use this file except in 
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/

import AbstractTaskWrapper from './AbstractTaskWrapper';
import MessageBuilder from '../../chat/proto/MessageBuilder'
import { GlobalContext, StnLogic } from '@ohos/mars'
import { MarsServiceStub } from '../service/MarsServiceStub'

/**
 * MarsTaskWrapper using nano protocol buffer encoding
 * <p></p>
 * Created by zhaoyuan on 16/2/29.
 */
export default abstract class NanoMarsTaskWrapper<T extends MessageBuilder, R extends MessageBuilder> extends AbstractTaskWrapper {

//    private static final String TAG = "Mars.Sample.NanoMarsTaskWrapper";

    protected request: T;
    protected response: R;

    public constructor(req: T, resp: R) {
        super();
        this.request = req;
        this.response = resp;
    }

    public req2buf() :ArrayBuffer {
        console.log("enter NanoMarsTaskWrapper.req2buf")
        this.onPreEncode(this.request);
        try {

            let Request = GlobalContext.getContext().getValue('request')
            // @ts-ignore
            let msg: protobuf.Builder.Message = new Request(this.request);
             // let tmpBuffer = new Uint8Array([ 10,10,116,101,115,116,95,116,111,107,101,110,18,3,98,99,99,26,3,97,108,108,34,5,100,100,102,102,103,42,1,48]);
                // const flatArray: ArrayBuffer = tmpBuffer.buffer;

                //            Log.d(TAG, "encoded request to buffer, [%s]", MemoryDump.dumpHex(flatArray));

                console.log("encoded request to buffer:" + MarsServiceStub.Uint8Array2String(new Uint8Array(msg.toArrayBuffer())));
                return msg.toArrayBuffer();
        } catch (e) {
            console.error("req2buf exception: " + e);
        }
        return null;
    }

    public buf2resp(buf: ArrayBuffer): number {
        try {
            console.info("decode response buffer, ["+new Uint8Array(buf)+"]");
            this.response.mergeFrom(buf);

            this.onPostDecode(this.response);
            return StnLogic.RESP_FAIL_HANDLE_NORMAL;

        } catch (e) {
            console.error("buf2resp exception: " + JSON.stringify(e));
        }

        return StnLogic.RESP_FAIL_HANDLE_TASK_END;
    }

    public abstract onPreEncode(request: T): void;

    public abstract onPostDecode(response: R): void;
}
